<?php

/**
 * Модель модуля событий
 */
class EventsModel extends DbModel {

    protected $_name = 'events';

    public function getEvents($id = 0, $pageNumber = 1) {
        $select = $this->_db->select()->from($this->_name)
                ->joinLeft('addons', $this->_name . '.module_id = addons.id', array('title AS module'))
                ->joinLeft('events_read', $this->_name . '.id = events_read.event_id', array('user_id AS user'))
                ->order('date DESC');
        if ($id > 0) {
            $res = $this->_db->fetchRow($select->where($this->_name . ".id = ?", (int) $id));
        } else {
            $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
            $paginator->setCurrentPageNumber($pageNumber);
            $model = new PaginatorModel();
            return $model->get($paginator);
        }
        return $res;
    }

    public function createEvent($title, $module, $oid = 0, $acl = 1, $alarm = false) {

        return $this->insert(
                        array(
                            'title' => $title,
                            'object_id' => (int) $oid,
                            'module_id' => (int) $module,
                            'acl' => (int) $acl,
                            'alarm' => $alarm,
                        )
        );
    }

    public function deleteEvent($id) {
        if ($id > 0) {
            $this->delete("id = " . $id);
            $this->_db->delete('events_read', 'event_id = ' . $id);
        }
    }
    
    public function userRead($uid, $eid) {
        $select = $this->_db->select()->from('events_read')->where('user_id = ' . $uid . ' AND event_id = ' . $eid );
        $res = $this->_db->fetchRow($select);
        if (!$res) {
            $this->_db->insert('events_read', array('user_id' => $uid, 'event_id' => $eid));
            return true;
        } else {
            return false;
        }
            
    }

}